package JPLXtandemGA;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import ngenes2.builder.BasicDIBuilder;
import ngenes2.evolver.Evolver;
import ngenes2.evolver.stop.MaxGeneration;
import ngenes2.examples.MaxOnes;
import ngenes2.individual.Individual;
import ngenes2.individual.LinearIndividual;
import ngenes2.ops.crossover.MidBreakCrossover;
import ngenes2.ops.mutator.PointMutation;
import ngenes2.ops.selector.KTournament;
import ngenes2.population.Population;
import ngenes2.util.Properties;

public class GAXTandem {

	public static void main(String[] args) {
		// final int indsize=4;
		final int popsize = 10;
		final int maxGen = 10;
		Properties props = new Properties()
			.put("population_size", popsize)
			.put("max_gene_value", 50)
			.put("tournament_size", 5)
			.put("max_generation", maxGen);

		java.util.Properties jprop = new java.util.Properties();
		try {
			jprop.load(new FileInputStream(args[0]));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		jprop.put("XML_FILE_NAME", "param.xml");
		jprop.put("TXT_PARAM_FILE_NAME", "GAXTParameters.csv");
		jprop.put("APPEND_FILE", "FALSE");

		BasicDIBuilder builder = new BasicDIBuilder()
			.with(props)
			.with(LinearIndividual.Factory.class)
			.with(new XTfitness(jprop))
			.with(ParameterGenerator.class)
			.with(ParameterMutator.class)
			.with(KTournament.class)
			.with(MaxGeneration.class)
			.with(MidBreakCrossover.class)
			.with(PointMutation.class)
			.with(MaxOnes.monitor);

		Evolver evolver = builder.evolver();
		Population pop = builder.population();
		evolver.evolve(pop);
		System.out.println( pop.stats().best() );
		int i = 0;
		try {
			File file = new File("fitness_scores.txt");
			FileWriter fw = new FileWriter(file);
			for (Iterator itr = pop.iterator(); itr.hasNext(); i++) {
				Individual idv = (Individual) itr.next();
				fw.write(i + "," + idv.fitness()+"\n");
			}
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
